package com.tzy.note.base.thread.sync;

/**
 * 不安全的买票
 * 线程不安全，有负数 -->解决办法 买票方法加synchronized 同步方法
 */
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();

        new Thread(station,"tzy1").start();
        new Thread(station,"tzy2").start();
        new Thread(station,"tzy3").start();
    }

}

class BuyTicket implements Runnable{
    //票
    private int ticketNums = 10;
    boolean flag = true; //外部停止方式
    @Override
    public void run() {
        while(flag){
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    //买票
    //synchronized 同步方法，锁的是this(调用者的对象)
    private synchronized void buy() throws InterruptedException {
        //判断是否有票
        if(ticketNums <= 0){
            flag = false;
            return;
        }
        Thread.sleep(200);
        //买票
        System.out.println(Thread.currentThread().getName() + "拿到" + ticketNums--);
    }
}

